<template>
  <div class="login-container">
    <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-position="left" label-width="0px"
      class="login-form">
      <h2 style="align-items: center;">注册</h2>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="registerForm.confirmPassword" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item prop="mail">
        <el-input type="mail" v-model="registerForm.email" placeholder="电子邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="value1" type="date" placeholder="Pick a day" style="width: 100%;" />
      </el-form-item>
      <div>
        <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
          style="margin-bottom: 10px;">
          <el-image v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100%" fit="contain" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </div>
      <div class="bottom-div">
        <el-button class="bottom-div-button" style="margin:0;" type="primary" color="black"
          @click="handleRegister">注册</el-button>
        <el-button class="bottom-div-button" style="margin:0;" type="primary" color="black"
          @click="this.$router.push(`/login`)">返回登录页面</el-button>
      </div>

    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import { inject } from "vue";
export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        email: ''
      },
      registerRules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: this.validatePasswordConfirmation, trigger: 'blur' }
        ]
      },
      value1: '',
      cos: inject("$cos"),
      cosConfig: inject("$cosConfig")
    };
  },
  methods: {
    validatePasswordConfirmation(rule, value, callback) {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致!"));
      } else {
        callback();
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          // 调用注册接口
          axios.post(
            "/api/userT/register",
            {
              name: this.registerForm.username,
              password: this.registerForm.password,
              email: this.registerForm.email,
              birthday: this.convertDateString,
            }).then((res) => {
              console.log(res);
              if (res.data.code === 1) {
                console.log(this.rawImage)
                this.cos.uploadFile({
                  Bucket: this.cosConfig.Bucket, /* 填写自己的 bucket，必须字段 */
                  Region: this.cosConfig.Region,     /* 存储桶所在地域，必须字段 */
                  Key: `webexp/${res.data.data}`,              /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
                  Body: this.rawImage, // 上传文件对象
                  SliceSize: 1024 * 1024 * 5,     /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
                  onProgress: function (progressData) {
                    console.log(JSON.stringify(progressData));
                  },
                  onFileFinish: function (err, data, options) {   /* 非必须 */
                    window.alert("注册成功");
                    setTimeout(() => {
                      this.$router.push("/login");
                    }, 1000);
                  }
                }, function (err, data) {
                  if (err) {
                    console.log('上传失败', err);
                  } else {
                    console.log('上传成功');
                  }
                });
              } else {
                window.alert("注册失败");
              }
            })
        } else {
          console.log("注册失败!");
          window.alert("注册失败");
        }
      });
    },
    beforeAvatarUpload(file) {
      this.imageUrl = URL.createObjectURL(file);
      console.log(this.imageUrl);
      this.rawImage = file;
      console.log(this.rawImage);
    },
  },
  computed: {
    convertDateString() {
      var date = new Date(this.value1);
      var year = date.getFullYear();
      var month = ("0" + (date.getMonth() + 1)).slice(-2); // getMonth() returns 0-11, so we add 1
      var day = ("0" + date.getDate()).slice(-2); // for padding zero to single digit date

      return year + "-" + month + "-" + day;
    },
  },
};
</script>

<style>
.login-container {
  flex-direction: row;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /* 使容器高度充满视口 */
  width: '100%';
  background-color: #f5f7fa;
}

.login-form {
  /* flex-direction: row; */
  /* display: flex; */
  width: 50%;
  /* 根据需要调整宽度 */
  /* max-width: 300px; 设置最大宽度以防止过大屏幕下表单过宽 */
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.avatar-uploader .avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  width: 100%;

  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>